package at.tasat.util;

import java.util.Iterator;

public final class IntStack implements Iterable<Integer>, Cloneable {
	private final int[] values;
	private int top;

	public IntStack(int capacity) {
		this(new int[capacity], 0);
	}

	private IntStack(int[] values, int top) {
		this.values = values;
		this.top = top;
	}

	public int capacity() {
		return values.length;
	}

	public int size() {
		return top;
	}

	public int get(int index) {
		assert inRange(index);
		return values[index];
	}

	public void push(int value) {
		assert top < values.length;
		values[top++] = value;
	}

	public int pop() {
		assert top > 0;
		return values[--top];
	}

	public int peek() {
		return values[top - 1];
	}

	public Iterator<Integer> iterator() {
		return new Iterator<Integer>() {
			private int cursor;

			@Override
			public boolean hasNext() {
				return cursor < top;
			}

			@Override
			public Integer next() {
				return Integer.valueOf(values[cursor++]);
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}

		};
	}

	private boolean inRange(int index) {
		return 0 <= index && index < top;
	}

	public IntStack clone() {
		return new IntStack(values.clone(), top);
	}
}
